package entities;

import exceptions.NonexistentEntityException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityNotFoundException;
import javax.persistence.Persistence;
import javax.persistence.Query;

/**
 *
 * @author sha
 */
public class DaftarUser {

    public DaftarUser() {
        emf = Persistence.createEntityManagerFactory("CeritaUnyilPU"); 
    }

    private EntityManagerFactory emf = null;

    public EntityManager getEntityManager() {
        return emf.createEntityManager();
    }
    
    public boolean checkUser(String username) {
        boolean result = false;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT count(o) FROM Users AS o WHERE o.username=:uname");
            q.setParameter("uname", username);
            int jumlahUser = ((Long) q.getSingleResult()).intValue();
            if (jumlahUser > 0) {
                result = true;
            }
        } finally {
            em.close();
        }
        return result;
    }

    public List<Users> getUsers() {
        List<Users> users = new ArrayList<Users>();

        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT a FROM Users AS a");
            users = q.getResultList();

        } finally {
            em.close();
        }
        return users;
    }
    
    public Users getUserFromName(String username) {
        Users user = null;
        EntityManager em = getEntityManager();
        try {
            boolean hasilCheck = this.checkUser(username);
            if (hasilCheck) {
                Query q = em.createQuery("SELECT object(o) FROM User AS o WHERE o.username=:uname");
                q.setParameter("usr", username);
                user = (Users) q.getSingleResult();
            }
        } finally {
            em.close();
        }
        return user;
    }

    public Users findUsers(Integer id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Users.class, id);
        } finally {
            em.close();
        }
    }

    public boolean check(String username, String password) {
        boolean result = false;
        EntityManager em = getEntityManager();
        try {
            Query q = em.createQuery("SELECT count(a) FROM Users AS a WHERE a.username=:uname AND a.password=:pass");
            q.setParameter("uname", username);
            q.setParameter("pass", password);
            int jumlahUser = ((Long) q.getSingleResult()).intValue();
            if (jumlahUser == 1) {
                result = true;
            }
        } finally {
            em.close();
        }
        return result;
    }
    
    public void rekamUser(Users user) {
        EntityManager em = getEntityManager();
        boolean hasilCheck1 = checkUser(user.getUsername());
        if (!hasilCheck1) {
            em.getTransaction().begin();
            try {
                em.persist(user);
                em.getTransaction().commit();
            } catch (Exception e) {
                em.getTransaction().rollback();
            } finally {
                em.close();
            }
        } else {
            try {
                throw new MyException("Username telah ada");
            } catch (MyException ex) {
                Logger.getLogger(DaftarUser.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }
    
    public void updateUsers(Users user) {
        EntityManager em = getEntityManager();
        try {
            em.getTransaction().begin();
            em.merge(user);
            em.getTransaction().commit();
        } finally {
            em.close();
        }
    }
    
    public void deleteUsers(Integer id) throws NonexistentEntityException{
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Users user;
            try {
                user = em.getReference(Users.class, id);
                user.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The user with id " + id + " no longer exists.", enfe);
            }
            em.remove(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public Users getUsers(String username, String password) {
        Users user = null;
        EntityManager em = getEntityManager();
        try {
            boolean hasilCheck = this.check(username, password);
            if (hasilCheck) {
                Query q = em.createQuery("SELECT a FROM Users AS a WHERE a.username=:uname AND a.password=:pass");
                q.setParameter("uname", username);
                q.setParameter("pass", password);
                user = (Users) q.getSingleResult();
            }
        } finally {
            em.close();
        }
        return user;
    }

    public Users findUser(Long id) {
        EntityManager em = getEntityManager();
        try {
            return em.find(Users.class, id);
        } finally {
            em.close();
        }
    }
    public boolean isUsernameExist(String kode) {
        DaftarUser daftarUser = new DaftarUser();
        List<Users> listUser = daftarUser.getUsers();
        Iterator<Users> iterator = listUser.iterator();
        Users tes = new Users();

        while (iterator.hasNext()) {
            tes = iterator.next();
            if (kode.equalsIgnoreCase(tes.getUsername())) {
                return true;
            }
        } return false;
    }
    
    public boolean isPasswordExist(String nama) {
        DaftarUser daftarUser = new DaftarUser();
        List<Users> listUser = daftarUser.getUsers();
        Iterator<Users> iterator = listUser.iterator();
        Users tes = new Users();

        while (iterator.hasNext()) {
            tes = iterator.next();
            if (nama.equalsIgnoreCase(tes.getPassword())) {
                return true;
            }
        } return false;
    }

    public void edit(Users user) {
       EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            user = em.merge(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
        }
    }

    public void destroy(long iduser) throws NonexistentEntityException {
        EntityManager em = null;
        try {
            em = getEntityManager();
            em.getTransaction().begin();
            Users user;
            try {
                user = em.getReference(Users.class, iduser);
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("user belum dipilih.", enfe);
            }
            em.remove(user);
            em.getTransaction().commit();
        } finally {
            if (em != null) {
                em.close();
            }
          }
    }
}